/********************************************************************++

Copyright (c) Microsoft Corporation. All rights reserved.

************************************************************************/

using System;
using System.Data;
using System.Configuration;
using System.Collections.ObjectModel;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Microsoft.Health;
using Microsoft.Health.Web;
using Microsoft.Health.ItemTypes;
using PFSync;

public partial class _Default : HealthServicePage
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        ConfigurationSettings.AppSettings["ApplicationCertificateFileName"] =
            MapPath(@"\cert\WildcatApp-75038c07-90b9-4f77-b7e9-1440e824fdc9.pfx");
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["User"] == null)
        {
            User u = new User();

            // See if user exists
            if (!PFSync.User.UserExists(PersonInfo.PersonId))
            {
                // Create the user and save them
                u = new User();
                u.PersonIdHV = PersonInfo.PersonId.ToString();
                u.RecordIdHV = PersonInfo.GetSelfRecord().Id.ToString();

                u.save();
            }
            else
                u = PFSync.User.RestoreByPersonIdGuid(PersonInfo.PersonId);

            u.Name = PersonInfo.Name;
            Session["User"] = u;
        }

        // Make sure user information is correct in case of database changes
        if (Session["User"] != null)
            Session["User"] = PFSync.User.RestoreByPersonIdGuid(PersonInfo.PersonId);

        // If the session user contains no PatientFusion ID, have them log in
        if (((User)Session["User"]).PatientIdPF == "" && Request["oauth_token"] == null)
        {
            string strNewRequestTokenUrl = FusionToken.GenerateRequestTokenUrl(ConfigurationManager.AppSettings["FusionUser"],
                ConfigurationManager.AppSettings["FusionPass"], 
                ConfigurationManager.AppSettings["AppLocation"]);

            if (strNewRequestTokenUrl.Length > 0)
            {
                string strRequestToken = FusionToken.GetOauthToken(strNewRequestTokenUrl);
                string strLoginUrl = "";
                //Append the Request Token in the login page url and do the redirect
                if (strRequestToken != string.Empty)
                {
                    strLoginUrl = ConfigurationManager.AppSettings["FusionLogin"] + "?oauth_token=" + strRequestToken;
                    Response.Redirect(strLoginUrl, true);
                }
            }
        }

        if (Request["oauth_token"] != null)
        {
            // Validate the oauth token if we have it
            try
            {
                User user = (User)Session["User"];
                Guid g = new Guid(Request["oauth_token"]);

                user.PatientIdPF = Request["oauth_token"].ToString();
                user.save();
            }
            catch (Exception ex)
            {
            }
        }

        Guid appID = new Guid(System.Configuration.ConfigurationSettings.AppSettings["ApplicationId"]);
        string healthServiceURL = System.Configuration.ConfigurationSettings.AppSettings["HealthServiceUrl"];
        OfflineWebApplicationConnection connection = new OfflineWebApplicationConnection(appID, healthServiceURL, PersonInfo.PersonId);
        
        // Authenticate connection
        connection.Authenticate();
        HealthRecordAccessor accessor = new HealthRecordAccessor(connection, PersonInfo.GetSelfRecord().Id);
        HealthRecordItemCollection info = accessor.GetItemsByType(BasicV2.TypeId);

        BasicV2 basic = (BasicV2)info[0];

        // Add all of the items in demographics to the label
        UserInfo.Text += PersonInfo.Name;
        UserInfo.Text += " (<span style='font-weight: bold'>" + basic.BirthYear.Value + "</span>)<br />";

        if (basic.StateOrProvince != null && basic.City != null)
        {
            UserInfo.Text += basic.Country + "<br />";
            UserInfo.Text += basic.City + ", " + basic.StateOrProvince + "<br />";
            UserInfo.Text += basic.PostalCode;
        }

        else if (basic.StateOrProvince != null && basic.City == null)
        {
            UserInfo.Text += basic.StateOrProvince + ", " + basic.Country + "<br />";
            UserInfo.Text += basic.PostalCode;
        }

        else
            UserInfo.Text += basic.Country + ", " + basic.PostalCode;
    }
}
